import * as net from 'net';
import { initHandler, dispatchCommand } from './handlers';
import { logger } from '../../utils/logger';
import { ServerInfo, ClientInfo } from '../../types';
import { BrowserWindow } from 'electron';
import { parseCommand, printBuffer } from './utils';
const { v4: uuidv4 } = require('uuid');

const PORT = 10000;

const serverInfo: ServerInfo = {
    ip: '127.0.0.1',
    port: PORT,
    clients: []
};


const server = net.createServer((socket) => {
    const clientId = uuidv4();
    logger.info('客户端已连接', clientId);
    const clientInfo: ClientInfo = {
        clientId: clientId,
        ip: socket.remoteAddress || 'unknown',
        sendMsg: '',
        receiveMsg: ''
    };
    serverInfo.clients.push(clientInfo);

    socket.on('data', (data) => {
        logger.info('服务端收到数据:', data.toString());
        try{
            printBuffer(data, 'binary');
            printBuffer(data, 'hex');
        }catch{
           console.log('打印失败！');
        }
       

        const { command, payload } = parseCommand(data);
        try {
            dispatchCommand(command, socket, payload, clientInfo);
            updateRenderer();
        } catch (error) {
            logger.error('处理命令时出错:', error);
            socket.write('错误: 无法处理命令');
        }
    });

    socket.on('end', () => {
        logger.info('客户端已断开连接');
        serverInfo.clients = serverInfo.clients.filter(client => client.clientId !== clientId);
        updateRenderer();
    });

    socket.on('error', (err) => {
        logger.error('Socket错误:', err);
        serverInfo.clients = serverInfo.clients.filter(client => client.clientId !== clientId);
        updateRenderer();
    });
});
let mainWindow: BrowserWindow | null = null;
const updateRenderer = () => {
    //更新服务端的渲染界面
    if (mainWindow) {
        mainWindow.webContents.send('update-server-info', serverInfo);
    }

};

export const createTcpServer = (window: BrowserWindow) => {
    mainWindow = window;
    initHandler(window)
    server.listen(PORT, () => {
        logger.info(`服务器正在监听端口 ${PORT}`);
    });
};
